<?php
/**
 * Date: 2017/11/10
 * Time: 10:08
 * Author: zeronlee
 */

namespace App\Http\Controllers\Backend\Log;


use App\Http\Controllers\Controller;
use App\Models\Access\User;
use App\Models\Ogz;
use App\Models\App;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Log;
use Illuminate\Support\Facades\DB;
use  Illuminate\Database\Query\Builder;


class LogController extends Controller
{

    /**日志列表首页
     * @param Request $request
     * @return $this
     */
    public function index(Request $request)
    {
        $fields = "";
        $where = array();
        $add=array();
        $startTime = $request->startTime;
        $endTime = $request->endTime;
        $searchKeywords = htmlspecialchars($request->searchKeywords);
        if ($startTime && $endTime) {
            $add['startTime']=$startTime;
            $add['endTime']=$endTime;
            if ($startTime < $endTime) {
                $where = array(["log.created_at", ">=", $startTime],
                    ["log.created_at", "<=", $endTime]);
            } elseif ($startTime >= $endTime) {
                return back()->with("log_error", "查询信息错误");
                exit();
            }
        } elseif ($startTime && !$endTime) {
            $add['startTime']=$startTime;
            $where = array(["log.created_at", ">=", $startTime]);
        } elseif (!$startTime && $endTime) {
            $add['endTime']=$endTime;
            $where = array(["log.created_at", "<=", $endTime]);
        } elseif (!$startTime && !$endTime) {
        }
        if($searchKeywords)
        {
            $add['searchKeywords']=$searchKeywords;
        }
//            DB::connection()->enableQueryLog();
        $fields = DB::table("log")
            ->join('users', 'users.id', '=', 'log.user_id')
            ->where(function ($query) use ($where) {
                if (!empty($where)) {
                    $query->where($where);
                }
            })
            ->Where(function ($query) use ($searchKeywords) {
                if ($searchKeywords) {
                    $key = '%' . $searchKeywords . '%';
                    $query->where('users.real_name', 'like', $key)
                        ->orWhere('users.name', 'like', $key);
                }
            })
            ->select('log.*', 'users.name','users.real_name')
            ->orderBy('log.id', 'desc')
            ->paginate(10);
        if(!empty($add)){
            $page = isset($page) ? $request['page'] : 1;
            $add['page']=$page;
            $fields = $fields->appends($add);
        }

            //add more element if you have more search terms

        return view('backend.log.index')->with('lists', $fields);
    }
}